import 'package:cms/models/const/single_const.dart';
import 'package:cms/models/single.dart';
import 'package:common/export/tools.dart';
import 'package:common/utils/lara_press_date.dart';
import 'package:components/lara_press_box.dart';
import 'package:components/lara_press_img.dart';
import 'package:components/lara_press_text.dart';
import 'package:components/loaders/row_img_loading.dart';
import 'package:flutter/material.dart';

class LaraPressRowImgSingleItem extends StatelessWidget {
  final SingleModel single;
  final bool isLoading;
  final VoidCallback? onTap;
  final bool showCategory;
  const LaraPressRowImgSingleItem({
    super.key,
    required this.single,
    this.isLoading = false,
    this.onTap,
    this.showCategory = true,
  });

  @override
  Widget build(BuildContext context) {
    if (isLoading) {
      return LaraPressBoxConvenience.card(child: LaraPressRowImgLoading());
    }
    final rowListOptions =
        single.rowListOptions ?? LaraPressSingleConst.rowListOptions;
    final displayData = rowListOptions.listDisplayData!;
    final isMultiImage = _shouldShowMultiImage(rowListOptions);

    final contentWidgets = _buildContentWidgets(context, displayData);

    return LaraPressBoxConvenience.card(
      borderRadius: 0,
      onTap: onTap,
      child: Column(
        spacing: 10.h,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          isMultiImage
              ? _buildMultiImageLayout(contentWidgets)
              : _buildSingleImageLayout(contentWidgets),
          _buildFooterWidget(context),
        ],
      ),
    );
  }

  // 构建底部数据组件
  Widget _buildFooterWidget(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          spacing: 5.w,
          children: [
            LaraPressIcon(
              icon: Clarity.eye_line,
              size: 14.sp,
              type: LaraPressTextType.listMeta,
            ),
            LaraPressText(
              text: "${single.actions?.views}",
              type: LaraPressTextType.listMeta,
            ),
          ],
        ),
        Row(
          spacing: 5.w,
          children: [
            LaraPressIcon(
              icon: Clarity.heart_line,
              size: 14.sp,
              type: LaraPressTextType.listMeta,
            ),
            LaraPressText(
              text: "${single.actions?.likes}",
              type: LaraPressTextType.listMeta,
            ),
          ],
        ),
        Row(
          spacing: 5.w,
          children: [
            LaraPressIcon(
              icon: Clarity.bookmark_line,
              size: 14.sp,
              type: LaraPressTextType.listMeta,
            ),
            LaraPressText(
              text: "${single.actions?.favorites}",
              type: LaraPressTextType.listMeta,
            ),
          ],
        ),
        Row(
          spacing: 5.w,
          children: [
            LaraPressIcon(
              icon: Clarity.chat_bubble_line,
              size: 14.sp,
              type: LaraPressTextType.listMeta,
            ),
            LaraPressText(
              text: "${single.commentCount}",
              type: LaraPressTextType.listMeta,
            ),
          ],
        ),
      ],
    );
  }

  /// 判断是否应该显示多图
  bool _shouldShowMultiImage(RowListOptions options) {
    return options.imageDisplay == "auto" &&
        single.images != null &&
        single.images!.length >= 2;
  }

  /// 构建内容组件列表
  List<Widget> _buildContentWidgets(
    BuildContext context,
    List<String> displayData,
  ) {
    final widgets = <Widget>[
      LaraPressText(
        text: "${single.title}",
        type: LaraPressTextType.listTitle,
        fontWeight: FontWeight.bold,
      ),
    ];

    // 添加作者信息区域
    if (_hasAuthorInfo(displayData)) {
      widgets.add(_buildAuthorInfoRow(context, displayData));
    }

    // 添加摘要
    if (displayData.contains("excerpt")) {
      widgets.add(_buildExcerptWidget());
    }

    // 添加多图
    if (_shouldShowMultiImage(
      single.rowListOptions ?? LaraPressSingleConst.rowListOptions,
    )) {
      widgets.add(_buildMultiImageRow());
    }

    // 添加分类标签
    if (displayData.contains("category") && _hasCategories() && showCategory) {
      widgets.add(_buildCategoryRow(context));
    }

    return widgets;
  }

  /// 检查是否有作者信息需要显示
  bool _hasAuthorInfo(List<String> displayData) {
    return displayData.contains("author_avatar") ||
        displayData.contains("author") ||
        displayData.contains("date");
  }

  /// 检查是否有分类
  bool _hasCategories() {
    return single.categories != null && single.categories!.isNotEmpty;
  }

  /// 构建作者信息行
  Widget _buildAuthorInfoRow(BuildContext context, List<String> displayData) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          spacing: 5,
          children: [
            if (displayData.contains("author_avatar"))
              LaraPressImg(
                img: "${single.author?.avatar}",
                width: 16.h,
                height: 16.h,
                radius: 16.h,
              ),
            if (displayData.contains("author"))
              LaraPressText(
                text: "${single.author?.name}",
                type: LaraPressTextType.listMeta,
              ),
          ],
        ),
        if (displayData.contains("date"))
          LaraPressText(
            text: LaraPressDate.formatAgo("${single.date?.created}"),
            type: LaraPressTextType.listMeta,
          ),
      ],
    );
  }

  /// 构建摘要组件
  Widget _buildExcerptWidget() {
    return LaraPressText(
      text: "${single.excerpt}",
      type: LaraPressTextType.listContent,
      maxLines: 2,
    );
  }

  /// 构建多图行
  Widget _buildMultiImageRow() {
    return Row(
      spacing: 10.w,
      children: single.images!.take(3).map((image) {
        return Expanded(
          child: LaraPressImg(
            img: image,
            height: single.images!.length > 2 ? 80.h : 100.h,
            radius: 6.r,
          ),
        );
      }).toList(),
    );
  }

  /// 构建分类标签行
  Widget _buildCategoryRow(BuildContext context) {
    return Row(
      children: single.categories!.map((category) {
        return OutlinedButton(
          style: OutlinedButton.styleFrom(
            side: BorderSide(color: Theme.of(context).primaryColor),
            backgroundColor: Colors.transparent,
            visualDensity: VisualDensity.compact,
            padding: EdgeInsets.symmetric(horizontal: 10.w),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(4.r),
            ),
          ),
          onPressed: () {
            context.pushNamed(
              'cms-categories-detail',
              pathParameters: {'id': category.id.toString()},
            );
          },
          child: LaraPressText(
            text: category.name ?? "",
            type: LaraPressTextType.listMeta,
            color: Theme.of(context).primaryColor,
          ),
        );
      }).toList(),
    );
  }

  /// 构建多图布局
  Widget _buildMultiImageLayout(List<Widget> contentWidgets) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      spacing: 6.h,
      children: contentWidgets,
    );
  }

  /// 构建单图布局
  Widget _buildSingleImageLayout(List<Widget> contentWidgets) {
    return Stack(
      children: [
        Positioned(
          top: 0,
          left: 0,
          bottom: 0,
          child: LaraPressImg(
            img: "${single.cover}",
            width: .3.sw,
            radius: 6.r,
          ),
        ),
        Container(
          margin: EdgeInsets.only(left: .32.sw),
          child: Column(
            spacing: 6.h,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: contentWidgets,
          ),
        ),
      ],
    );
  }
}
